from itertools import combinations
import random


def generate_six_arrays(numbers):
    """
    将16个数字分成6个数组，确保任意5个数字都能在某个数组中找到。
    """
    if len(numbers) != 16:
        raise ValueError("必须提供16个数字！")

    # Step 1: 生成所有可能的6个数字组合
    all_combinations = list(combinations(numbers, 6))

    # Step 2: 初始化结果
    result = []
    used_combinations = set()

    # Step 3: 创建6个数组，覆盖所有组合
    while len(result) < 6:
        remaining_combinations = [
            comb for comb in all_combinations if comb not in used_combinations
        ]

        # 贪心选择一个组，优先覆盖剩余组合最多的组
        if remaining_combinations:
            best_group = set(remaining_combinations[0])  # 初始选择第一个组合
            max_cover = 0

            for comb in remaining_combinations:
                candidate_group = set(comb)
                covered_count = sum(
                    1 for c in combinations(candidate_group, 5) if set(c) in remaining_combinations
                )
                if covered_count > max_cover:
                    best_group = candidate_group
                    max_cover = covered_count

            result.append(best_group)
            # 标记已覆盖的组合
            for comb in combinations(best_group, 5):
                used_combinations.add(comb)
        else:
            break

    # Step 4: 确保结果只有6组
    while len(result) > 6:
        result.pop()

    # 如果组数不够6，用剩余数字填补
    all_numbers_used = set().union(*result)
    remaining_numbers = set(numbers) - all_numbers_used
    while len(result) < 6 and remaining_numbers:
        new_group = set(random.sample(remaining_numbers, 6))  # 随机选择6个数字
        result.append(new_group)

    # 转换为列表格式
    return [list(group) for group in result]


if __name__ == "__main__":
    # Step 1: 让用户输入或随机生成16个数字
    user_input = input("请输入16个数字，用空格分隔 (或直接按Enter随机生成): ")
    if user_input.strip():
        numbers = list(map(int, user_input.split()))
        if len(numbers) != 16 or len(set(numbers)) != 16:
            print("输入无效！请提供16个不重复的数字。")
            exit(1)
    else:
        numbers = random.sample(range(1, 100), 16)

    print(f"使用的数字集合: {numbers}")

    # Step 2: 生成满足条件的6个数组
    arrays = generate_six_arrays(numbers)

    # Step 3: 输出结果
    print("生成的6个数组如下：")
    for i, arr in enumerate(arrays, 1):
        print(f"数组 {i}: {arr}")